package global

import (
	"context"
	"github.com/go-redis/redis/v8"
	"log"
	"os"
	"time"

	"daily-blog/model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func InitDB() {
	var err error
	confDB := GVA_CONFIG.DB
	// 构建dns
	dns := confDB.User + ":" + confDB.Pwd +
		"@tcp(" + confDB.Host + confDB.Port + ")/" +
		confDB.Name + "?charset=utf8mb4&parseTime=True&loc=Local"

	// db logger
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second, // 慢 SQL 阈值
			LogLevel:                  logger.Info, // 日志级别
			IgnoreRecordNotFoundError: false,       // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  true,        // 彩色打印
		},
	)

	// 初始化DB对象
	if GVA_DB, err = gorm.Open(mysql.Open(dns), &gorm.Config{
		SkipDefaultTransaction:                   true, // 跳过单条语句的事务处理
		Logger:                                   newLogger,
		DisableForeignKeyConstraintWhenMigrating: true, // 禁用创建外键约束
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 禁用表名加s
		},
	}); err != nil {
		log.Panic("数据库初始化失败", err)
	}
	err = GVA_DB.Use(&TracePlugin{})
	if err != nil {
		log.Println("trace plugin err", err)
		return
	}
	//initTables(GVA_DB)

	//redis
	err = initRedisClient()
	if err != nil {
		log.Panic("redis初始化失败", err)
		return
	}
}
func initTables(db *gorm.DB) {
	//db.AutoMigrate(&model.Post{})
	//db.AutoMigrate(&model.Tag{})
	//db.AutoMigrate(&model.PostTag{})
	db.AutoMigrate(&model.Category{})
	//db.AutoMigrate(&model.Comment{})
	//db.AutoMigrate(&model.User{})
}
func initRedisClient() (err error) {
	redisConfig := GVA_CONFIG.Redis
	GVA_RDB = redis.NewClient(&redis.Options{
		Addr:     redisConfig.Addr,
		Password: redisConfig.Pwd,
		DB:       redisConfig.Name,
		PoolSize: redisConfig.Size,
	})
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_, err = GVA_RDB.Ping(ctx).Result()
	return err
}
